import React, { Component } from 'react';
import { Form, Input, Modal, message, Icon, Upload } from 'antd'
import { isAuthenticated } from '../../utils/session'
import { json } from '../../utils/ajax'
import { connect } from 'react-redux'

const { TextArea } = Input;

const store = connect(
  (state) => ({ user: state.user })
)

@store @Form.create()
class CreateModal extends Component {
  state = {
    uploading: false
  }
  onCancel = () => {
    this.props.form.resetFields()
    this.props.toggleVisible(false)
  }
  onOk = () => {
    this.props.form.validateFieldsAndScroll((errors, values) => {
      if (!errors) {
        this.onCreate(values)
      }
    })
  }
  componentDidMount () {
    if (this.props.typeStr === 'edit') {
      console.log('edit')
      const typeData = this.props.typeData;
      this.props.form.setFieldsValue({
        icon: typeData.icon
      })
      this.props.form.setFieldsValue({
        title: typeData.title
      })
      this.props.form.setFieldsValue({
        description: typeData.description
      })
    }
  }
  onCreate = async (values) => {
    console.log(values, this.props.typeData, 'aaaa')
    let res;
    if (this.props.typeStr === 'edit') {
      res = await json.post('/works/update', { ...values, id: this.props.typeData.id })
    } else {
      res = await json.post('/works/create', values)
    }
    if (res.status === 0) {
      this.props.onCreated()  //更新外面的数据
      this.onCancel()
    }
  }
  _normFile = (e) => {
    if (e.file.response && e.file.response.data) {
      console.log(e.file.response.data.url, 'e.file.response.data.url')
      return e.file.response.data.url
    } else {
      return ''
    }
  }
  render () {
    const { getFieldDecorator, getFieldValue, setFieldsValue } = this.props.form
    const { uploading } = this.state
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    }
    let icon = getFieldValue('icon')
    const uploadProps = {
      name: "icon",
      listType: "picture-card",
      headers: {
        Authorization: `Bearer ${isAuthenticated()}`,
      },
      action: `${process.env.REACT_APP_BASE_URL}/upload?isImg=1`,
      showUploadList: false,
      accept: "image/*",
      onChange: (info) => {
        if (info.file.status !== 'uploading') {
          this.setState({
            uploading: true
          })
        }
        if (info.file.status === 'done') {
          this.setState({
            uploading: false
          })
          message.success('上传头像成功')
        } else if (info.file.status === 'error') {
          this.setState({
            uploading: false
          })
          message.error(info.file.response.message || '上传头像失败')
        }
      }
    }
    return (
      <Modal
        visible={this.props.visible}
        title='新增视频类型'
        centered
        onCancel={this.onCancel}
        okButtonProps={{ disabled: !this.props.user.isAdmin }}
        onOk={this.onOk}
      >
        <Form {...formItemLayout}>
          <Form.Item label={'类型名称'}>
            {getFieldDecorator('title', {
              rules: [
                { required: true, message: '请输入类型名称' },
              ]
            })(
              <Input placeholder='请输入类型名称' />
            )}
          </Form.Item>
          <Form.Item label={'类型描述'}>
            {getFieldDecorator('description', {
              rules: [
                { required: true, message: '请类型描述' },
              ]
            })(
              <TextArea placeholder='请输入类型描述' />
            )}
          </Form.Item>
          <Form.Item label={'类型icon'}>
            {getFieldDecorator('icon', {
              rules: [{ required: true, message: '请上传用户头像' }],
              getValueFromEvent: this._normFile,     //将上传的结果作为表单项的值（用normalize报错了，所以用的这个属性）
            })(
              <Upload {...uploadProps} style={styles.avatarUploader}>
                {icon ? <img src={icon} alt="icon" style={styles.avatar} /> : <Icon style={styles.icon} type={uploading ? 'loading' : 'plus'} />}
              </Upload>
            )}
          </Form.Item>
        </Form>

      </Modal>
    );
  }
}

const styles = {
  avatarUploader: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    width: 150,
    height: 150,
    backgroundColor: '#fff'
  },
  icon: {
    fontSize: 28,
    color: '#999'
  },
  avatar: {
    maxWidth: '100%',
    maxHeight: '100%',
  },
}

export default CreateModal;